<template>
    <div>
        <el-form label-width="100px">
            <el-form-item label="SPU名称">
                <el-input v-model="SpuParams.spuName" placeholder="请你输入SPU名称" />
            </el-form-item>
            <el-form-item label="SPU品牌">
                <el-select v-model="SpuParams.tmId" placeholder="请你选择品牌" style="width: 240px">
                    <el-option v-for="item in AllTradeMarkList" :label="item.tmName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input v-model="SpuParams.description" type="textarea" placeholder="请你输入描述" />
            </el-form-item>
            <el-form-item label="SPU照片">
                <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handleBefore">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" style="width: 100%;height: 100%;" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="SPU销售属性">
                <el-select v-model="saleAttrIdAndValueName"  :placeholder="unSelectSaleAttr.length?`还未选择${unSelectSaleAttr.length}个`:'暂无数据可选择'" style="width: 240px">
                    <el-option v-for="item in unSelectSaleAttr" :label="item.name" :value="`${item.id}:${item.name}`" />
                </el-select>
                <el-button @click="addSaleAttr" :disabled="saleAttrIdAndValueName?false :true" type="primary" style="margin-left: 20px;">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    添加属性
                </el-button>
            </el-form-item>
            <el-form-item label="">
                <el-table :data="SaleAttrList" border>
                    <el-table-column type="index" label="序号" width="80px" />
                    <el-table-column prop="saleAttrName" label="属性名" />
                    <el-table-column prop="str" label="属性值">
                        <template #default="scope">
                            <el-tag style="margin:0 5px" v-for="(item,index) in scope.row.spuSaleAttrValueList" :key="item.id" closable  type="primary" @close="scope.row.spuSaleAttrValueList.splice(index,1)">
                                {{ item.saleAttrValueName }}
                            </el-tag>
                            <input v-model="scope.row.saleAttrValue" v-if="scope.row.flag == true" style="width: 70px;" @blur="editTag(scope.row)" />
                            <el-button v-else @click="addTag(scope.row)" type="success" size="small" icon="Plus"></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="Operations">
                        <template #default="scope">
                            <el-button size="small" type="danger" icon="Delete" @click="SaleAttrList.splice(scope.$index,1)">
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="save">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup lang="ts">
import {ref,computed} from 'vue'
import type { SpuData,AllTradeMark,SpuHasImg,SaleAttrResponseData,HasSaleAttrResponseData,
    Trademark,SpuImg,HasSaleAttr,SaleAttrValue,
    SaleAttr
} from '@/api/product/spu/type'
import { reqAllTradeMark,reqSpuImageList,reqSpuHasSaleAttr,reqAllSalAttr,reqAddOrUpdateSpu } from '@/api/product/spu/index'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
let $emit = defineEmits(['changeScene'])
//点击取消的事件
const cancel = ()=>{
    $emit('changeScene', { scene: 0, params: 'update' })
}

let AllTradeMarkList = ref<Trademark[]>([])
let imgList = ref<SpuImg[]>([])
let SaleAttrList = ref<SaleAttr[]>([])
let allSaleAttr = ref<HasSaleAttr[]>([])
let SpuParams = ref<SpuData>({
  category3Id: '',//三级分类id
  spuName: '',//spu名称
  description: '',//spu描述
  tmId: '',//选中的spu品牌id
  spuImageList: [],//照片墙
  spuSaleAttrList: [],//spu销售属性
})
let saleAttrIdAndValueName = ref<string>('')
//图片相关
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
//获取数据的接口
const initHasSpuData = async(spu:SpuData)=>{
    SpuParams.value = spu
    //获取全部品牌的数据
    let res:AllTradeMark = await reqAllTradeMark()
    //获取某一个品牌旗下全部售卖商品的图片
    let res1:SpuHasImg = await reqSpuImageList(spu.id as number)
    //获取已有的spu销售属性的数据
    let res2:SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
    //获取整个项目全部spu的销售属性
    let res3:HasSaleAttrResponseData = await reqAllSalAttr()
    AllTradeMarkList.value = res.data
    imgList.value = res1.data.map((item)=>{
        return{
            name:item.imgName,
            url:item.imgUrl
        }
    })
    SaleAttrList.value = res2.data
    allSaleAttr.value = res3.data
 
}
//图片预览事件
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile)=>{
      dialogImageUrl.value = uploadFile.url!
      dialogVisible.value = true
}
//图片移除事件
const handleRemove:UploadProps['onRemove'] = (uploadFile, uploadFiles)=>{
    console.log(uploadFile, uploadFiles)
}
//图片上传之前的事件
const handleBefore:UploadProps['beforeUpload'] = (rawFile)=>{
  if (rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4){
      return true
    }else{
      ElMessage({
        message: '上传文件大小应小于4M',
        type: 'error',
      })
    }
    
  } else  {
    ElMessage({
      message: '上传图片类型必须是PNG|JPG|GIF',
      type: 'error',
    })
    return false
  }
  return true
}

let unSelectSaleAttr = computed(()=>{
    let unSelectArr = allSaleAttr.value.filter((item)=>{
        return SaleAttrList.value.every((item1)=>{
            return item.name !== item1.saleAttrName
        })
    })
    return unSelectArr
})

const addSaleAttr = ()=>{
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  SaleAttrList.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}
//点击添加tag的按钮
const addTag = (row:SaleAttr)=>{
    row.saleAttrValue = ''
    row.flag = true
}
//input失去焦点
const editTag = (row:SaleAttr)=>{
    const {baseSaleAttrId,saleAttrValue} = row
    let newSaleAttrValue:SaleAttrValue={
        baseSaleAttrId,
        saleAttrValueName:saleAttrValue as string,
    }
    if(saleAttrValue?.trim() === ''){
        ElMessage({
            type:'error',
            message:"属性值不能为空"
        })
        return
    }
    let repeat = row.spuSaleAttrValueList.find((item)=>{
        return item.saleAttrValueName === saleAttrValue
    })
    if(repeat){
        ElMessage({
            type:'error',
            message:'属性值重复'
        })
        return
    }
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    row.flag = false
}

//添加或更新的接口请求
const save = async()=>{
    // 处理数据
    SpuParams.value.spuImageList = imgList.value.map((item:any)=>{
        return{
            imgName:item.name,
            imgUrl:(item.response && item.response.data) || item.url
        }
    })
    SpuParams.value.spuSaleAttrList = SaleAttrList.value
    let res = await reqAddOrUpdateSpu(SpuParams.value)
    if(res.code == 200){
        ElMessage({
            type:'success',
            message:SpuParams.value.id ? '更新成功' : '添加成功'
        })
        //告诉父组件切换场景
      $emit('changeScene', { scene: 0, params: SpuParams.value.id  ? 'update' :'add' })
    }else{
        ElMessage({
            type:'error',
            message:SpuParams.value.id ? '更新失败' : '添加失败'
        })
    }

}
//添加数据处理
const initAddSpu = async(c3Id:number | string)=>{
    Object.assign(SpuParams.value,{
        category3Id: '',//三级分类id
        spuName: '',//spu名称
        description: '',//spu描述
        tmId: '',//选中的spu品牌id
        spuImageList: [],//照片墙
        spuSaleAttrList: [],//spu销售属性
    })
    //清空图片
    imgList.value = []
    SaleAttrList.value = []
    saleAttrIdAndValueName.value = ''
    SpuParams.value.category3Id = c3Id
    //获取全部品牌的数据
    let res:AllTradeMark = await reqAllTradeMark()
    //获取某一个品牌旗下全部售卖商品的图片
    let res3:HasSaleAttrResponseData = await reqAllSalAttr()
    AllTradeMarkList.value = res.data
    allSaleAttr.value = res3.data
}
defineExpose({initHasSpuData,initAddSpu})
</script>
<style></style>